package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a09_分割回文串复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/10
 */
public class a09_分割回文串复习3 {
    public static void main(String[] args) {
        a09_分割回文串复习3 tst = new a09_分割回文串复习3();
        tst.partition("aab");
    }

    public List<List<String>> partition(String s) {
        char[] chars = s.toCharArray();
        List<List<String>> result = new ArrayList<>();
        LinkedList<String> path = new LinkedList<>();
        traversal(result, path,chars,0);
        return result;
    }

    private void traversal(List<List<String>> result,
                           LinkedList<String> path,
                           char[] chars,
                           int startIdx){
        if(startIdx == chars.length){
            result.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i < chars.length; i++) {
            //判断是不是回文子串
            if (!check(chars, startIdx, i)) {
                continue;
            }
            path.add(split(chars, startIdx, i));
            traversal(result, path, chars, i + 1);
            path.removeLast();
        }
    }

    private boolean check(char[] chars,int leftIdx,int rightIdx){
        while (leftIdx <= rightIdx){
            if (chars[leftIdx] != chars[rightIdx]) {
                return false;
            }
            leftIdx++;
            rightIdx--;
        }
        return true;
    }

    private String split(char[] chars,int leftIdx,int rightIdx){
        StringBuilder sb = new StringBuilder();
        while (leftIdx <= rightIdx) {
            sb.append(chars[leftIdx]);
            leftIdx++;
        }
        return sb.toString();
    }
}
